package com.jt.assistant.http

import android.util.Log
import androidx.annotation.NonNull
import com.jt.assistant.base.GlobalConfig.JTMS_URL_BASE
import me.jessyan.retrofiturlmanager.RetrofitUrlManager
import okhttp3.ConnectionPool
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import java.io.IOException
import java.util.concurrent.TimeUnit

/**
 */
class RetrofitClient {

    companion object {
        fun getInstance() = SingletonHolder.INSTANCE
        private lateinit var retrofit: Retrofit
    }

    private object SingletonHolder {
        val INSTANCE = RetrofitClient()
    }

    init {
        retrofit = Retrofit.Builder()
            .client(getOkHttpClient())
            .addConverterFactory(JsonConverterFactory.create())
            .baseUrl(JTMS_URL_BASE)
            .build()
    }

    private fun getOkHttpClient(): OkHttpClient {

        return RetrofitUrlManager.getInstance().with(
            OkHttpClient.Builder()
                .connectTimeout(20L, TimeUnit.SECONDS)
                .addNetworkInterceptor(getInterceptor())
                .addInterceptor(Retry(3))
                .writeTimeout(20L, TimeUnit.SECONDS)
                .connectionPool(ConnectionPool(8, 15, TimeUnit.SECONDS))
                .connectTimeout(20L, TimeUnit.SECONDS)
        ).build()
    }

    internal class Retry(  //最大重试次数
        var maxRetry: Int
    ) : Interceptor {
        private var retryNum = 3 //假如设置为3次重试的话，则最大可能请求4次（默认1次+3次重试）
        @Throws(IOException::class)
        override fun intercept(@NonNull chain: Interceptor.Chain): Response {
            val request = chain.request()
            var response = chain.proceed(request)
            Log.i("Retry", "num:$retryNum")
            while (!response.isSuccessful && retryNum < maxRetry) {
                retryNum++
                Log.i("Retry", "num:$retryNum")
                response = chain.proceed(request)
            }
            return response
        }
    }

    private fun getInterceptor(): Interceptor? {
        val interceptor = HttpLoggingInterceptor()
        //显示日志
        interceptor.level = HttpLoggingInterceptor.Level.BODY
        return interceptor
    }

    fun <T> create(service: Class<T>?): T =
        retrofit.create(service!!) ?: throw RuntimeException("Api service is null!")
}